/*
 * @Description: video 模型类
 * @Author: Junhuang
 * @Date: 2022-02-15 11:27:52
 * @LastEditTime: 2022-02-22 22:01:14
 * @LastEditors: Junhuang
 * @Reference: 
 */
'use strict';
// 引入
const crypto = require('crypto');
module.exports = app => {
  const { INTEGER, STRING, DATE, ENUM, TEXT } = app.Sequelize;
  // 配置（重要：一定要配置详细，一定要！！！）
  const Video = app.model.define('video', {
    id: {
      type: INTEGER(20),
      primaryKey: true,
      autoIncrement: true
    },
    title: {
      type: STRING(100),
      allowNull: false,
      defaultValue: '',
      comment: '视频标题'
    },
    cover: {
      type: STRING,
      allowNull: true,
      defaultValue: '',
      comment: '视频封面'
    },
    category_id: {
      type: INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: '分类id'
    },
    user_id: {
      type: INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: '用户id'
    },
    duration: {
      type: INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: '总时长'
    },
    description: {
      type: TEXT,
      allowNull: false,
      defaultValue: '',
      comment: '视频描述',
    },
    play_count: {
      type: INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: '播放量'
    },
    danmu_count: {
      type: INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: '弹幕量'
    },
    created_time: {
      type: DATE,
      // 获取器，对获取的数据库中的字段进行处理，此处将数据库中的时间字段转换为timestamp
      get() {
        const val = this.getDataValue('created_time')
        return (new Date(val)).getTime()
      }
    },
    updated_time: {
      type: DATE,
      // 获取器，对获取的数据库中的字段进行处理，此处将数据库中的时间字段转换为timestamp
      get() {
        const val = this.getDataValue('updated_time')
        return (new Date(val)).getTime()
      }
    }
  }, {
    timestamps: true, // 是否自动写入时间戳
    tableName: 'video', // 自定义数据表名称
  });

  //关联关系
  Video.associate = function (models) {
    // 关联作者
    Video.belongsTo(app.model.User, {
      foreignKey: 'user_id'
    });
    // 关联类别
    Video.belongsTo(app.model.Category, {
      foreignKey: 'category_id'
    });
    // 关联视频
    Video.hasMany(app.model.VideoDetail, {
      foreignKey: 'video_id',
      sourceKey: 'id'
    })
  }

  return Video;
};